package com.system.controller;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.common.base.utils.MD5Encode;
import com.common.utils.HttpUtils;
import com.common.utils.StringUtils;
import com.common.web.resp.vo.ResponseInfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.system.service.ISysLoginService;
import com.system.service.ISysMenuService;
import com.system.service.ISysRoleService;
import com.system.service.ISysStaffService;
import com.system.shiro.MyRealm;
import com.system.shiro.anthc.NoRoleException;
import com.system.vo.SysLoginLogVO;
import com.system.vo.SysMenuVO;
import com.system.vo.SysRoleVO;
import com.system.vo.SysStaffVO;

@Controller
@RequestMapping
public class LoginController extends FormAuthenticationFilter  {
	
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    
    @Resource
    private ISysMenuService menuService;
    
	@Resource
	private ISysStaffService staffService;
	
	@Resource
	private ISysRoleService roleService;
	
	@Resource
	private MyRealm myRealm;
    
    @Resource
    private ISysLoginService iSysLoginService;
	@RequestMapping(value = "/login")
	public String login(HttpServletRequest request,
		HttpServletResponse response, Model model, RedirectAttributes attr) {
		String exceptionClassName = (String)request.getAttribute("shiroLoginFailure");
		 String error = null;
        if(UnknownAccountException.class.getName().equals(exceptionClassName)) {
            error = "用户名/密码错误";
        } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
            error = "用户名/密码错误";
        } else if("randomCodeError".equals(exceptionClassName)) {
        	error = "验证码错误";
        } else if(LockedAccountException.class.getName().equals(exceptionClassName)){
        	error="用户已被禁止登录";
        } else if(NoRoleException.class.getName().equals(exceptionClassName)){
        	error="用户不具有系统任何角色";
        }
        model.addAttribute("error", error);
        Subject subject= SecurityUtils.getSubject();
        Session session=subject.getSession();
        Object s= session.getAttribute("user");
        if(s!=null){
        	subject.logout();
        }
        return "view-system/login";
	}
	
	@RequestMapping(value = "/index")
	public String index(HttpServletRequest request, HttpServletResponse response,String roleId){
		Subject subject=SecurityUtils.getSubject();
		Session session=subject.getSession();
		SysStaffVO staff = (SysStaffVO) session.getAttribute("user");
		if(roleId == null || "".equals(roleId)) {
			String staffId = staff.getStaffId();
			roleId = staff.getRoleId();
			SysLoginLogVO addVo = new SysLoginLogVO();
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			addVo.setLoginLogId(uuid);
			addVo.setStaffId(staffId);
			addVo.setOrgId(staff.getOrgId());
			addVo.setRoleId(staff.getRoleId());
			addVo.setLoginDate(new Date());
			addVo.setLoginIp(HttpUtils.getIpAddr(request));
			try {
				iSysLoginService.addLoginLog(addVo);
			} catch (Exception e) {
				e.printStackTrace();
			}
			SimplePrincipalCollection pl = (SimplePrincipalCollection) subject.getPrincipals();
			myRealm.clearCachedAuthorizationInfo(pl);
		}else{
			SysRoleVO sysRoleVO = roleService.findRoleById(roleId);
			staff.setRole(sysRoleVO);
			session.setAttribute("user",staff);
		}
		List<String> pList = staffService.findMenuIdByRoleId(roleId);
		List<SysMenuVO> menuList = menuService.findMenuSByMenuID(pList);
		ObjectMapper om=new ObjectMapper();
		try {
			String json=om.writeValueAsString(menuList);
			String str=StringEscapeUtils.escapeHtml(json);
			request.setAttribute("menus", str);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return "view-system/index";
   }

   @RequestMapping("/modifiyPsw")
   @ResponseBody
   public ResponseInfo modifiyPsw(@RequestParam("oldPsw") String oldPsw, @RequestParam("newPsw") String newPsw){
	   Subject subject=SecurityUtils.getSubject();
	   Session session=subject.getSession();
	   SysStaffVO staff = (SysStaffVO) session.getAttribute("user");
	   if(StringUtils.notBlank(oldPsw) && StringUtils.notBlank(newPsw)){
		   String oldP = MD5Encode.encode(oldPsw);
		   String newP = MD5Encode.encode(newPsw);
		   if(!oldP.equals(staff.getStaffPsw())){
			   return ResponseInfo.errorInfo("原密码不正确，请重新输入！","4000");
		   }
		   try {
			   staffService.modifiyPsw(newP,staff.getStaffId());
			   ResponseInfo info = new ResponseInfo();
			   info.setSuccess(true);
			   info.setMessage("密码修改成功！");
			   info.setCode("2000");
			   return info;
		   } catch (Exception e) {
			   e.printStackTrace();
		   }
	   }

		return ResponseInfo.errorInfo("密码修改失败，请稍后再试！","4000");
   }

   @RequestMapping("/echarts")
   public String testEcharts(){
		return "view-system/echarts";
   }
}
